from flask import request

from flask import Blueprint
from app.utils import json, get_age_by_birthday
from db import db
from db.models import UserInfo

user_api = Blueprint('user', __name__)


# 设置用户信息
@user_api.route('/v1/setUserInfo', methods=['POST'])
def setUserInfo():
    device_id = request.json.get('device_id')
    if device_id is None:
        return json(400, "device_id is required", "")
    height_range = request.json.get('height')
    if height_range is None:
        return json(400, "height is required", "")
    weight_range = request.json.get('weight')
    if weight_range is None:
        return json(400, "weight is required", "")
    birthday = request.json.get('age')
    if birthday == '':
        age = 0
    else:
        age = get_age_by_birthday(birthday)
    print("年龄：", age)
    gender = request.json.get('gender')
    if gender is None:
        gender = 0

    # 查询
    user_info = UserInfo.query.filter_by(device_id=device_id).first()
    if user_info is None:
        user = UserInfo(device_id=device_id, height_range=height_range, weight_range=weight_range, age=age,
                        gender=gender)
        db.session.add(user)
        db.session.commit()
    else:
        user_info.height_range = height_range
        user_info.weight_range = weight_range
        user_info.age = age
        user_info.gender = gender
        db.session.commit()

    return json(200, "success", "")


# 获取用户信息
@user_api.route('/v1/getUserInfo', methods=['GET'])
def getUserInfo():
    device_id = request.args.get('device_id')
    if device_id == "":
        return json(400, "device_id is required", "")

    user_info = UserInfo.query.filter_by(device_id=device_id).first()

    if user_info is None:
        return json(200, '', [])
    else:
        return json(200, "", {
            "device_id": user_info.device_id,
            "height": user_info.height_range,
            "weight": user_info.weight_range,
            "gender": user_info.gender,
            "created_at": user_info.created_at.strftime("%Y-%m-%d %H:%M:%S")
        })


# 获取用户信息
def get_user_info(device_id):
    user_info = UserInfo.query.filter_by(device_id=device_id).first()
    if user_info is None:
        return []
    else:
        return {
            "height_range": user_info.height_range,
            "weight_range": user_info.weight_range,
            "gender": user_info.gender,
        }
